# -*- coding:utf-8 -*-
"""
Author：Administrator
Date:2023年02月23日
"""

import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX

# from docx.enum.text import WD_ALIGN_PARAGRAPH


# 创建自定义函数实现超链接功能
def add_hyperlink(paragraph,  url,text):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')
    u=docx.oxml.shared.OxmlElement('w:u')
    u.set(docx.oxml.shared.qn('w:val'),'dotted')
    rPr.append(u)
    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)
    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)
    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True
    return hyperlink


myDocument = docx.Document("散文名篇.docx")
myParagraph = myDocument.paragraphs[1]
add_hyperlink(myParagraph, 'https://www.baidu.com/', '使用百度搜索了解更多内容。')

myDocument.save("02散文名篇.docx")
